package com.slfx.gen.develop;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;
import java.util.Collections;
import java.util.Properties;

/**
 * @author zengqingfa
 * @className CodeAutoGenerator
 * @description
 * @create 2022/9/30 18:51
 */
@Slf4j
public class CodeAutoGenerator {

	/**
	 * 代码生成的路径
	 */
	private String outputDir;
	/**
	 * 代码生成的包名
	 */
	private String packageName;
	/**
	 * 需要生成的表名
	 */
	private String[] includeTables = {};
	/**
	 * 作者
	 */
	private String author;
	/**
	 * 使用环境
	 */
	private String profile;
	/**
	 * 数据库
	 */
	private String database;

    public static String URL;
    public static String USERNAME;
    public static String PASSWORD;

	public void run() {
		Properties props = getProperties();
		if ("dev".equals(profile)) {
			URL = props.getProperty("dev.spring.datasource.url").replaceAll("database", database);
			USERNAME = props.getProperty("dev.spring.datasource.username");
			PASSWORD = props.getProperty("dev.spring.datasource.password");
		} else if ("test".equals(profile)) {
			URL = props.getProperty("test.spring.datasource.url").replaceAll("database", database);
			USERNAME = props.getProperty("test.spring.datasource.username");
			PASSWORD = props.getProperty("test.spring.datasource.password");
		}
        // 数据源配置
        DataSourceConfig.Builder dataSourceConfig = new DataSourceConfig.Builder(URL, USERNAME, PASSWORD);
        FastAutoGenerator.create(dataSourceConfig)
                .globalConfig(builder -> {
                    builder.author(author) // 设置作者
                            .enableSwagger() // 开启 swagger 模式
                            .fileOverride() // 覆盖已生成文件
							.dateType(DateType.ONLY_DATE)
                            .outputDir(outputDir + "/src/main/java"); // 指定输出目录
                })
                .packageConfig(builder -> {
                    builder.parent(packageName) // 设置父包名
                            //.moduleName("ibs-materail") // 设置父包模块名
                            .entity("entity")
                            .service("service")
                            .serviceImpl("service.impl")
                            .mapper("mapper")
                            .xml("mapper.mapping")
                            .controller("controller")
                            .other("other")
                            .pathInfo(Collections.singletonMap(OutputFile.mapperXml, outputDir + "/src/main/resource")); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder.addInclude(includeTables)
                            //.addTablePrefix()
                            .entityBuilder()
                            //.superClass()
                            //.formatFileName("%sDto")
                            .enableChainModel()
                            .enableLombok()
                            .enableRemoveIsPrefix()
                            .controllerBuilder()
                            .enableRestStyle()
                            .formatFileName("%sController")
                            .serviceBuilder()
                            .formatServiceFileName("%sService")
                            .formatServiceImplFileName("%sServiceImpl")
                            .mapperBuilder()
                            .enableMapperAnnotation()
                            .enableBaseResultMap()
                            .enableBaseColumnList()
                            .formatMapperFileName("%sMapper")
                            .formatXmlFileName("%sMapper");
                })
                .templateConfig(builder -> {
                    /**
                     * 配置生成文件的模板
                     */
                    builder.entity("/generators/entity.java")
                            .service("/generators/service.java")
                            .serviceImpl("/generators/serviceImpl.java")
                            .mapper("/generators/mapper.java")
                            .mapperXml("/generators/mapper.xml")
                            .controller("/generators/controller.java");
                })
                .injectionConfig(builder -> {
                    builder.beforeOutputFile((tableInfo, objectMap) -> {
                        System.out.println("tableInfo: " + tableInfo.getEntityName() + " objectMap: " + objectMap.size());
                    });
                })
                .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板，默认的是Velocity引擎模板
                .execute();
    }

	// 获取配置文件
	private Properties getProperties() {
		// 读取配置文件
		Resource resource = new ClassPathResource("/core.properties");
		Properties props = new Properties();
		try {
			props = PropertiesLoaderUtils.loadProperties(resource);
		} catch (IOException e) {
			//e.printStackTrace();
			log.error("获取配置文件错误", e);
		}
		return props;
	}

	public CodeAutoGenerator(String outputDir, String packageName, String author, String profile, String database, String[] includeTables) {
		this.outputDir = outputDir;
		this.packageName = packageName;
		this.includeTables = includeTables;
		this.author = author;
		this.profile = profile;
		this.database = database;
	}

	public static void main(String[] args) {
		String[] includeTables = {"data_auth","system_project","project_asset","user_data_auth"};
		CodeAutoGenerator code = new CodeAutoGenerator("D:/mybatis", "com.slfx.data.permission",
				"slfx", "dev", "auth",includeTables);
		code.run();
	}


}
